package com.example.view;


import com.example.dianping.R;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;

public class SideBar extends View {
	
	private TextView dialogText;

	public SideBar(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
	}

	public SideBar(Context context) {
		super(context);
	}
	
	public void setTextView(TextView dialogText) {
		this.dialogText = dialogText;
	}
	
	private Paint paint = new Paint();
	private OnTouchingLetterChangedListener letterChangedListener;

	public static String[] sidebar = { "热门", "A", "B", "C", "D", "E", "F",
			"G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S",
			"T", "U", "V", "W", "X", "Y", "Z" };

	private int choose;
	
	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);

		paint.setColor(Color.GRAY);
		paint.setTypeface(Typeface.DEFAULT_BOLD);
		paint.setTextSize(20);

		int height = getHeight();
		int width = getWidth();

		System.out.println(height);
		System.out.println(width);

		int each_height = height / sidebar.length;

		for (int i = 0; i < sidebar.length; i++) {
			float x = width / 2 - paint.measureText(sidebar[i]) / 2;
			float y = (i + 1) * each_height;

			canvas.drawText(sidebar[i], x, y, paint);
		}
	}

	public interface OnTouchingLetterChangedListener {
		public void onTouchingLetterChanged(String s);
	}

	public void setOnTouchingLetterChangedListener(
			OnTouchingLetterChangedListener onTouchingLetterChangedListener) {
		this.letterChangedListener = onTouchingLetterChangedListener;
	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent event) {

		final int action = event.getAction();
		final float y = event.getY();
		final OnTouchingLetterChangedListener listener = letterChangedListener;

		final int c = (int) (y / getHeight() * sidebar.length);
		switch (action) {
		case MotionEvent.ACTION_UP:
			setBackgroundResource(android.R.color.transparent);
			invalidate();
			dialogText.postDelayed(new Runnable() {

				@Override
				public void run() {
					dialogText.setVisibility(View.INVISIBLE);

				}
			}, 1 * 1000);
			break;

		default:
			setBackgroundResource(R.drawable.sidebar_background);
			
			dialogText.setVisibility(View.VISIBLE);
			dialogText.setText(String.valueOf(sidebar[c]));
			dialogText.setTextSize(TypedValue.COMPLEX_UNIT_SP, 34);
			
			
			if (c > 0 && c < sidebar.length) {
				if (listener != null) {
					listener.onTouchingLetterChanged(sidebar[c]);
				}
				choose = c;
				invalidate();
			}
			break;
		}

		return true;

	}

}
